package com.cn.transfer.jobhandler;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cn.transfer.common.constant.KeyConstant;
import com.cn.transfer.common.http.ApiClient;
import com.cn.transfer.common.vo.SalesPerformanceDashboard;
import com.cn.transfer.mapper.SalesPerformanceDashboardMapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author: weidian
 * @date: 2024/8/9 14:12
 * @Description: 拉取销售KPL看板
 */
@Slf4j
@Component
public class SalesPerformanceDashboardXxlJob {

    @Autowired
    private SalesPerformanceDashboardMapper salesPerformanceDashboardMapper;

    @XxlJob("SalesPerformanceDashboard")
    public void saleOrderUpdate() {
        Header[] headers = new Header[3];
        headers[0] = new BasicHeader("Accept", "application/json");
        headers[1] = new BasicHeader("Authorization", "Basic " + KeyConstant.SAP01);
        headers[2] = new BasicHeader("x-csrf-token", "Fetch");
        int cont = 0;
        boolean bale = true;
        while (bale) {
            JSONObject entries = ApiClient.sendGetRequest("https://my200654-api.s4hana.sapcloud.cn/sap/opu/odata/sap/YY1_KPI_CDS/YY1_KPI?$inlinecount=allpages&$skip=" + cont + "&$top=50", headers, null);
            String d = entries.getStr("d");
            JSONObject objects = JSONUtil.parseObj(d);
            String results = objects.getStr("results");
            String __count = objects.getStr("__count");
            log.info("拉取销售KPL看板总条目===>" + __count);
            JSONArray objectss = JSONUtil.parseArray(results);
            List<SalesPerformanceDashboard> salesPerformanceDashboards = JSONUtil.toList(objectss, SalesPerformanceDashboard.class);
            for (SalesPerformanceDashboard salesPerformanceDashboard : salesPerformanceDashboards) {

                if (salesPerformanceDashboard.getLastTimesTampLastTimesTamp() != null) {
                    long lct = Long.parseLong(extractTimestamp(salesPerformanceDashboard.getLastTimesTampLastTimesTamp()));
                    LocalDateTime dateTime2 = convertTimestampToLocalDateTime(lct);
                    String formattedDateTime2 = formatDateTime(dateTime2);
                    DateTime dateTime4 = new DateTime(formattedDateTime2, DatePattern.NORM_DATETIME_FORMAT);
                    salesPerformanceDashboard.setLastTimesTampLastTimesTamps(dateTime4);
                }
                if (salesPerformanceDashboard.getRateStartDate() != null) {
                    long lct = Long.parseLong(extractTimestamp(salesPerformanceDashboard.getRateStartDate()));
                    LocalDateTime dateTime2 = convertTimestampToLocalDateTime(lct);
                    String formattedDateTime2 = formatDateTime(dateTime2);
                    DateTime dateTime4 = new DateTime(formattedDateTime2, DatePattern.NORM_DATETIME_FORMAT);
                    salesPerformanceDashboard.setRateStartDates(dateTime4);
                }
                long let = Long.parseLong(extractTimestamp(salesPerformanceDashboard.getSalesDocumentDate()));
                LocalDateTime dateTime1 = convertTimestampToLocalDateTime(let);


                // 格式化为字符串
                String formattedDateTime1 = formatDateTime(dateTime1);

                DateTime dateTime3 = new DateTime(formattedDateTime1, DatePattern.NORM_DATETIME_FORMAT);

                salesPerformanceDashboard.setSalesDocumentDates(dateTime3);
                if ("CNY".equals(salesPerformanceDashboard.getSalesOrganizationCurrency())&& !"CNY".equals(salesPerformanceDashboard.getSO_TransactionCurrency())) {
                    double taxs1 = Double.parseDouble(salesPerformanceDashboard.getTotalPriceIncludingTaxs());
                    double taxs2 = Double.parseDouble(salesPerformanceDashboard.getTotalPriceExcludingTaxs());
                    double taxs3 = Double.parseDouble(salesPerformanceDashboard.getNetAmountOfBillings());
                    double taxs4 = Double.parseDouble(salesPerformanceDashboard.getGrossIncomes());
                    double taxs9 = Double.parseDouble(salesPerformanceDashboard.getPriceDetnExchangeRate());
                    double sun1;
                    double sun2;
                    double sun3;
                    double sun4;
                    if (salesPerformanceDashboard.getSO_TransactionCurrency().equals("RUB") ||
                            salesPerformanceDashboard.getSO_TransactionCurrency().equals("HKD")) {

                        sun1 = taxs1 != 0 ? taxs1 / taxs9 : 0.0;
                        sun2 = taxs2 != 0 ? taxs2 / taxs9 : 0.0;
                        sun3 = taxs3 != 0 ? taxs3 / taxs9 : 0.0;
                        sun4 = taxs4 != 0 ? taxs4 / taxs9 : 0.0;
                    } else {
                        sun1 = taxs1 != 0 ? taxs1 * taxs9 : 0.0;
                        sun2 = taxs2 != 0 ? taxs2 * taxs9 : 0.0;
                        sun3 = taxs3 != 0 ? taxs3 * taxs9 : 0.0;
                        sun4 = taxs4 != 0 ? taxs4 * taxs9 : 0.0;
                    }
                    salesPerformanceDashboard.setTotalPriceIncludingTaxs(String.valueOf(sun1));
                    salesPerformanceDashboard.setTotalPriceExcludingTaxs(String.valueOf(sun2));
                    salesPerformanceDashboard.setNetAmountOfBillings(String.valueOf(sun3));
                    salesPerformanceDashboard.setGrossIncomes(String.valueOf(sun4));

                } else {
                    if (!salesPerformanceDashboard.getSO_TransactionCurrency().equals("CNY")) {
                        double taxs1 = Double.parseDouble(salesPerformanceDashboard.getTotalPriceIncludingTaxs());
                        double taxs2 = Double.parseDouble(salesPerformanceDashboard.getTotalPriceExcludingTaxs());
                        double taxs3 = Double.parseDouble(salesPerformanceDashboard.getNetAmountOfBillings());
                        double taxs4 = Double.parseDouble(salesPerformanceDashboard.getGrossIncomes());
                        double taxs9 = Double.parseDouble(salesPerformanceDashboard.getExchangeRate());

                        double sun1;
                        double sun2;
                        double sun3;
                        double sun4;
                        if (salesPerformanceDashboard.getSO_TransactionCurrency().equals("RUB") ||
                                salesPerformanceDashboard.getSO_TransactionCurrency().equals("HKD")) {
                            sun1 = taxs1 != 0 ? taxs1 / taxs9 : 0.0;
                            sun2 = taxs2 != 0 ? taxs2 / taxs9 : 0.0;
                            sun3 = taxs3 != 0 ? taxs3 / taxs9 : 0.0;
                            sun4 = taxs4 != 0 ? taxs4 / taxs9 : 0.0;
                        } else {
                            sun1 = taxs1 != 0 ? taxs1 * taxs9 : 0.0;
                            sun2 = taxs2 != 0 ? taxs2 * taxs9 : 0.0;
                            sun3 = taxs3 != 0 ? taxs3 * taxs9 : 0.0;
                            sun4 = taxs4 != 0 ? taxs4 * taxs9 : 0.0;
                        }
                        salesPerformanceDashboard.setTotalPriceIncludingTaxs(String.valueOf(sun1));
                        salesPerformanceDashboard.setTotalPriceExcludingTaxs(String.valueOf(sun2));
                        salesPerformanceDashboard.setNetAmountOfBillings(String.valueOf(sun3));
                        salesPerformanceDashboard.setGrossIncomes(String.valueOf(sun4));

                    }
                }

            }
            int i = salesPerformanceDashboardMapper.insertSalesPerformanceDashboards(salesPerformanceDashboards);
            log.info("新增的条数"+i);
            if (salesPerformanceDashboards.size() != 50) {
                bale = false;
            }
            cont += 50;
        }
    }

    public static String extractTimestamp(String dateString) {
        // 使用正则表达式提取括号中的数字部分
        String timestamp = dateString.replaceAll("^/Date\\((\\d+)([\\+\\-]\\d+)?\\)/$", "$1");
        return timestamp;
    }

    public static LocalDateTime convertTimestampToLocalDateTime(long timestamp) {
        // 从时间戳转换为 Instant，再转换为 LocalDateTime
        Instant instant = Instant.ofEpochMilli(timestamp);
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

    public static String formatDateTime(LocalDateTime dateTime) {
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return dateTime.format(formatter);
    }
}
